import React, { useRef, useState, useEffect } from 'react';
import {
    PlusOutlined,
} from '@ant-design/icons';
import {
    Button,
    Input,
    message,
    Popconfirm
    // Badge
    // Tag, Space,
    // Menu, Dropdown
} from 'antd';
import {
    hasPermission,
    permissionCodes as pCodes
} from '@/routes/permission'
import YzhTable from '@com/YzhTable';
import api from '@/api/apiList'
import AddDialog from './add'
const AppManage = (props) => {
    const actionRef = useRef();
    let clientHeight = document.body.clientHeight
    const [scroll, setScroll] = useState(props.scroll || { x: 1500, y: clientHeight });
    const columns = [
        {
            title: '应用名称',
            dataIndex: 'appName',
            hideInSearch: true,
            // sorter: true,
            align: 'left',
            // valueType: 'indexBorder',
            // width: 220,
        },
        {
            title: '名称/编码',
            dataIndex: 'key',
            copyable: true,
            ellipsis: true,
            // sorter: true,
            hideInTable: true,
            // tip: '名称/编码',
            renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
                if (type === 'form') {
                    return null;
                }
                const status = form.getFieldValue('state');
                if (status !== 'open') {
                    return (
                        // value 和 onchange 会通过 form 自动注入。
                        <Input
                            // 组件的配置
                            {...fieldProps}
                            // 自定义配置
                            placeholder="请输入名称/编码"
                        />
                    );
                }
                return defaultRender(_);
            },
            formItemProps: {
                placeholder: '名称/编码',
                rules: [
                    {
                        required: false,
                        message: '此项为必填项',
                    },
                ],
            },
        },
        {
            title: '应用编码',
            dataIndex: 'appCode',
            hideInSearch: true,
            // sorter: true
        },
        {
            title: '应用链接',
            dataIndex: 'appLink',
            hideInSearch: true,
            // copyable: true,
            // sorter: true
        },
        {
            title: '排序',
            dataIndex: 'sort',
            // sorter: true,
            hideInSearch: true,
            fixed: 'right',
            align: 'center',
            order: 2,
            width: 250,
            render: (text, record, index, action) => {
                // console.log(text, record, action, '12312');
                const { current, total, pageSize } = action.pageInfo
                return hasPermission([pCodes.application.sort]) && [
                    <Button
                        disabled={current === 1 && index === 0}
                        type="link"
                        key="move-up"
                        onClick={() => onMove('up', record, action)}>
                        上移
                    </Button>,
                    <Button type="link"
                        disabled={total % pageSize === state.appList.length &&
                            index + 1 === state.appList.length}
                        onClick={() => onMove('down', record, action)}
                        key="move-down">
                        下移
                    </Button>,
                ]
            },
        },
        {
            title: '创建时间',
            key: 'showTime',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            sorter: true,
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateRange',
            hideInSearch: true,
            hideInTable: true,
            search: {
                transform: (value) => {
                    return {
                        startTime: value[0],
                        endTime: value[1],
                    };
                },
            },
        },
        {
            title: '操作',
            valueType: 'option',
            align: 'center',
            fixed: 'right',
            width: 140,
            render: (text, record, _, action) => [
                (hasPermission([pCodes.application.edit]) && <a type={'text'}
                    key="editable"
                    disabled={record.id === '0'}
                    onClick={() => onEdit(record)}>
                    编辑
                </a>),
                (hasPermission([pCodes.application.remove]) && <Popconfirm
                    key="delete"
                    placement="topRight"
                    title={<p key="desc" style={{ maxWidth: 200 }}>删除后该应用入口会被去除且无法进入，是否确认删除？</p>}
                    onConfirm={() => onDelete(record, action)}
                >
                    <a type={'text'} href={record.url} key="delete">
                        删除
                    </a>
                </Popconfirm>)
            ],
        },
    ];
    const [state, setState] = useState({
        form: {
            appCode: undefined,
            appImg: undefined,
            appLink: undefined,
            appName: undefined,
            id: undefined,
            key: undefined
        },
        appList: [],
        total: 0,
        dialogAddVisible: false
    })
    useEffect(() => {
        setScroll(props.scroll)
    }, [props.scroll])
    const onAdd = () => {
        setState({
            ...state,
            form: {
                appCode: undefined,
                appImg: undefined,
                appLink: undefined,
                appName: undefined,
                id: undefined,
                key: undefined
            },
            dialogAddVisible: true
        })
    }
    // 修改
    const onEdit = async (row) => {
        setState({
            ...state,
            dialogAddVisible: true,
            form: {
                appCode: row.appCode,
                appImg: row.appImg,
                appLink: row.appLink,
                appName: row.appName,
                id: row.id,
                key: row.key
            }
        })
    }
    const onSubmit = async (values) => {
        if (values) {
            setState({
                ...state,
                dialogAddVisible: false
            })
            let params = {
                appCode: values.appCode,
                appImg: values.appImg,
                appLink: values.appLink,
                appName: values.appName,
                key: values.key
            }
            let res = ''
            if (state.form.id) {
                params.id = state.form.id
                res = await api.app.edit({ ...params })
            } else {
                res = await api.app.add({ ...params })
            }
            res && res.success && message.success(res.message || '操作成功')
            actionRef.current.reload()
            // getTableData()
            return
        }
        setState({
            ...state,
            dialogAddVisible: false
        })
    }
    // 排序
    const onMove = async (type, record, action) => {
        let parentNode = state.appList
        let params = {
            "firstId": record.id,
            "firstOriginSortValue": record.sort,
            "secondId": 0,
            "secondOriginSortValue": 0
        }
        state.appList.map((el, index) => {
            if (record.id === el.id) {
                let nextIndex = type === 'up' ? index - 1 : index + 1
                if (parentNode[nextIndex]) {
                    params.secondId = parentNode[nextIndex].id
                    params.secondOriginSortValue = parentNode[nextIndex].sort
                }
            }
            return el
        })
        // console.log(params, 'action');
        let res = await api.app.sort({ ...params })
        res && res.success && message.success(res.message || '操作成功')
        action.reload()
        // getTableData()
    }
    // 删除
    const onDelete = async (record, action) => {
        let res = await api.app.remove({ id: record.id })
        res && res.success && message.success(res.message || '操作成功')
        action && action.reload()
        // getTableData()
    }
    const getTableData = async (params, sort, filter) => {
        // console.log(sort, filter);
        let res = await api.app.list({ ...params, currentPage: params.current })
        let data = res && res.result !== null ? res.result.records : []
        let total = res && res.result !== null ? res.result.page.totalRow : 0
        setState({
            ...state,
            total,
            appList: data
        })
        return { data, total, success: true };
    }
    let scrollY = hasPermission([pCodes.application.add]) ? scroll.y - 390 : scroll.y - 340
    return (
        <div className="yzh-app-list">
            <YzhTable
                columns={columns}
                // tableStyle={{ minHeight: scroll.y - 310 }}
                tableStyle={{ minHeight: scrollY, paddingTop: !hasPermission([pCodes.user.add]) && 20 }}
                scroll={{
                    x: scroll.x,
                    y: scrollY
                }}
                actionRef={actionRef}
                request={async (params = {}, sort, filter) => getTableData(params, sort, filter)}
                editable={{
                    type: 'multiple',
                }}
                rowKey="id"
                tableExtraRender={() => hasPermission([pCodes.application.add]) && [
                    <Button key="add" onClick={onAdd} icon={<PlusOutlined />} type="primary">
                        新增应用
                    </Button>,
                ]}
            />
            {state.dialogAddVisible ?
                <AddDialog {...state.form}
                    setAddDialog={onSubmit}
                    dialogAddVisible={state.dialogAddVisible} /> : null}
        </div>
    );
};
export default AppManage